package com.web.oa.controller;


import com.github.pagehelper.PageInfo;
import com.web.oa.pojo.ActiveEmployee;
import com.web.oa.pojo.Baoxiaobill;
import com.web.oa.service.BaoXiaoService;
import com.web.oa.service.WorkFlowService;
import com.web.oa.utils.Constants;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
public class WorkFlowController {
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private BaoXiaoService baoXiaoService;

    @RequestMapping("/myTaskList")
    public String getTaskList(Model model, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        ActiveEmployee activeEmployee = (ActiveEmployee) SecurityUtils.getSubject().getPrincipal();
        PageInfo<Task> pageInfo = workFlowService.findTaskListByName(activeEmployee.getName(), pageNum);
        model.addAttribute("pageInfo", pageInfo);
        return "workflow_task";
    }

    @RequestMapping("/add_process")
    public String add_process() {
        return "add_process";
    }

    //act_re_deployment
    @RequestMapping("/deployProcess")
    public String deployProcess(MultipartFile fileName, String processName) {
        try {
            workFlowService.saveDeployee(fileName.getInputStream(), processName);
        } catch (IOException exception) {
            exception.printStackTrace();
        }
        return "redirect:/processDefinitionList";
    }

    //act_re_procdef
    @RequestMapping("/processDefinitionList")
    public String processDefinitionList(Model model, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        PageInfo<Deployment> deploymentPageInfo = workFlowService.findDeploymentList(pageNum);

        PageInfo<ProcessDefinition> processDefinitionPageInfo = workFlowService.findProcessDefinitionList(pageNum);
        //放置到上下文对象中
        model.addAttribute("deploymentPageInfo", deploymentPageInfo);
        model.addAttribute("processDefinitionPageInfo", processDefinitionPageInfo);

        return "workflow_list";
    }

    @RequestMapping("/saveStartBaoxiao")
    public String saveStartBaoxiao(Baoxiaobill baoxiaobill) {
        baoxiaobill.setCreatdate(new Date());
        ActiveEmployee activeEmployee = (ActiveEmployee) SecurityUtils.getSubject().getPrincipal();
        baoxiaobill.setUserId(activeEmployee.getId());

        baoxiaobill.setState(1);
        baoXiaoService.saveBaoxiao(baoxiaobill);

        workFlowService.saveStartProcess(baoxiaobill.getId(), activeEmployee.getName());

        return "redirect:/myTaskList";
    }

    @RequestMapping("/viewTaskForm")
    public String viewTaskForm(String taskId, Model model) {

        Baoxiaobill baoxiaobill = workFlowService.findBaoxiaoBillByTaskId(taskId);
        List<Comment> list = workFlowService.findCommentByTaskId(taskId);
        List<String> outcomeList = workFlowService.findOutComeListByTaskId(taskId);

        model.addAttribute("baoxiaoBill", baoxiaobill);
        model.addAttribute("commentList", list);
        model.addAttribute("outcomeList", outcomeList);
        model.addAttribute("taskId", taskId);
        return "approve_baoxiao";
    }

    @RequestMapping("/submitTask")
    public String submitTask(long id, String taskId, String comment, String outcome) {
        //String username = ((Employee)session.getAttribute(Constants.GLOBLE_USER_SESSION)).getName();
        ActiveEmployee activeEmployee = (ActiveEmployee) SecurityUtils.getSubject().getPrincipal();
        String username = activeEmployee.getName();
        workFlowService.saveSubmitTask(id, taskId, comment, outcome, username);
        return "redirect:/myTaskList";
    }

    /**
     * 查看当前流程图（查看当前活动节点，并使用红色的框标注）
     */
    @RequestMapping("/viewCurrentImage")
    public String viewCurrentImage(String taskId, ModelMap model, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        /**一：查看流程图*/
        //1：获取任务ID，获取任务对象，使用任务对象获取流程定义ID，查询流程定义对象
        ProcessDefinition pd = null;
        Map<String, Object> map = null;
        try {
            pd = workFlowService.findProcessDefinitionByTaskId(taskId);

            model.addAttribute("deploymentId", pd.getDeploymentId());
            model.addAttribute("imageName", pd.getDiagramResourceName());
            /**二：查看当前活动，获取当期活动对应的坐标x,y,width,height，将4个值存放到Map<String,Object>中*/
            map = workFlowService.findCoordingByTask(taskId);

            model.addAttribute("acs", map);
        } catch (Exception e) {
            ActiveEmployee activeEmployee = (ActiveEmployee) SecurityUtils.getSubject().getPrincipal();
            PageInfo<Baoxiaobill> pageInfo = baoXiaoService.findLeaveBillById(activeEmployee.getEmployeeId(), pageNum);
            model.addAttribute("error", "查询不到这条记录，可能是流程已被删除");
            model.addAttribute("pageInfo", pageInfo);
            return "baoxiaobill";
        }

        return "viewimage";
    }

    /**
     * 查看流程图
     *
     * @throws Exception
     */
    @RequestMapping("/viewImage")
    public String viewImage(String deploymentId, String imageName, HttpServletResponse response, Model model, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) throws Exception {

        //2：获取资源文件表（act_ge_bytearray）中资源图片输入流InputStream
        InputStream in = null;
        try {
            in = workFlowService.findImageInputStream(deploymentId, imageName);
        } catch (Exception e) {
            ActiveEmployee activeEmployee = (ActiveEmployee) SecurityUtils.getSubject().getPrincipal();
            PageInfo<Baoxiaobill> pageInfo = baoXiaoService.findLeaveBillById(activeEmployee.getEmployeeId(), pageNum);
            model.addAttribute("error", "查询不到这条记录，可能是流程已被删除");
            model.addAttribute("pageInfo", pageInfo);
            return "baoxiaobill";
        }
        //3：从response对象获取输出流
        OutputStream out = response.getOutputStream();
        //4：将输入流中的数据读取出来，写到输出流中
        for (int b = -1; (b = in.read()) != -1; ) {
            out.write(b);
        }
        out.close();
        in.close();
        return null;
    }

    // 查看历史的批注信息
    @RequestMapping("/viewHisComment")
    public String viewHisComment(long id, ModelMap model, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        //1：使用报销单ID，查询报销单对象
        Baoxiaobill bill = baoXiaoService.findBaoxiaoBillById(id);
        model.addAttribute("baoxiaoBill", bill);
        //2：使用请假单ID，查询历史的批注信息
        List<Comment> commentList = null;
        try {
            commentList = workFlowService.findCommentByBaoxiaoBillId(id);

        } catch (Exception e) {
            ActiveEmployee activeEmployee = (ActiveEmployee) SecurityUtils.getSubject().getPrincipal();
            PageInfo<Baoxiaobill> pageInfo = baoXiaoService.findLeaveBillById(activeEmployee.getEmployeeId(), pageNum);
            model.addAttribute("error", "查询不到这条记录，可能是流程已被删除");
            model.addAttribute("pageInfo", pageInfo);
            return "baoxiaobill";
        }
        model.addAttribute("commentList", commentList);

        return "workflow_commentlist";
    }

    /**
     * 删除部署信息
     */
    @RequestMapping("/delDeployment")
    public String delDeployment(String deploymentId) {
        //使用部署对象ID，删除流程定义
        workFlowService.deleteProcessDefinitionByDeploymentId(deploymentId);
        return "redirect:/processDefinitionList";
    }

    @RequestMapping("/leaveBillAction_delete")
    public String leaveBillAction_delete(String id) {
        //使用部署对象ID，删除流程定义
        baoXiaoService.deleteBaoxiaoByBillId(id);
        return "redirect:/myBaoxiaoBill";
    }

    @RequestMapping("/viewCurrentImageByBill")
    public String viewCurrentImageByBill(long billId, ModelMap model, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        Task task = null;
        ProcessDefinition pd = null;
        Map<String, Object> map = null;
        try {
            String BUSSINESS_KEY = Constants.BAOXIAO_KEY + "." + billId;
            task = this.workFlowService.findTaskByBussinessKey(BUSSINESS_KEY);
            /**一：查看流程图*/
            //1：获取任务ID，获取任务对象，使用任务对象获取流程定义ID，查询流程定义对象
            pd = workFlowService.findProcessDefinitionByTaskId(task.getId());
            model.addAttribute("deploymentId", pd.getDeploymentId());
            model.addAttribute("imageName", pd.getDiagramResourceName());
            /**二：查看当前活动，获取当期活动对应的坐标x,y,width,height，将4个值存放到Map<String,Object>中*/
            map = workFlowService.findCoordingByTask(task.getId());

            model.addAttribute("acs", map);
        } catch (Exception e) {
            ActiveEmployee activeEmployee = (ActiveEmployee) SecurityUtils.getSubject().getPrincipal();
            PageInfo<Baoxiaobill> pageInfo = baoXiaoService.findLeaveBillById(activeEmployee.getEmployeeId(), pageNum);
            model.addAttribute("error", "查询不到这条记录，可能是流程已被删除");
            model.addAttribute("pageInfo", pageInfo);
            return "baoxiaobill";
        }


        return "viewimage";
    }


}
